﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using Netkk.Common;
using Netkk.Common.Interfaces.Repositories;
using Netkk.Common.Interfaces.Services;
using Netkk.Common.Models;
using Netkk.Core;
using Netkk.Models;

namespace Netkk.Controllers
{
    [HandleError]
    public class HomeController : BaseControler
    {
        private readonly IAppointmentService appointmentService;
        private readonly INewsService newsService;
        private readonly ITwitterRepository twitterRepository;

        public HomeController(
            IAppointmentService appointmentService,
            INewsService newsService,
            ITwitterRepository twitterRepository)
        {
            this.appointmentService = appointmentService;
            this.newsService = newsService;
            this.twitterRepository = twitterRepository;
        }

        public ActionResult Index()
        {
            IEnumerable<string> formattedTweets;

            try
            {
                formattedTweets = CacheWrapper.Load("tweets",
                                                    new TimeSpan(0, 30, 0),
                                                    () => twitterRepository.GetFormattedUserTimeLine(
                                                              5).ToList());
            }
            catch (WebException)
            {
                formattedTweets = new List<string> { "Twitter nicht erreichbar" };
            }

            News news = newsService.GetLatestNews() ?? new News
                                                           {
                                                               Title = String.Empty
                                                           };
            Appointment appointment = appointmentService.GetLatestAppointment() ?? new Appointment
                                                                                      {
                                                                                          Title = String.Empty,
                                                                                          Description = String.Empty
                                                                                      };

            HomeModel model = new HomeModel
                                  {
                                      Tweets = formattedTweets,
                                      News = NewsModel.Create(news),
                                      Appointment = AppointmentModel.Create(appointment)
                                  };
            return View(model);
        }
    }
}